<?php 
define('ROOT_PATH',  str_replace('\\', '/', dirname(dirname(dirname(dirname(__FILE__)))))."/");
ini_set('date.timezone','Asia/Shanghai');


require_once(ROOT_PATH."lib/db_init.php");//引入数据库文件
require_once(ROOT_PATH."lib/lib_base.php");
require_once(ROOT_PATH."lib/lib_safe.php");
require_once(ROOT_PATH."application/constant/Constant.php");
require_once ROOT_PATH. "application/www/pay/lib/WxPay.Api.php";
require_once ROOT_PATH. "application/www/pay/example/WxPay.JsApiPay.php";
require_once ROOT_PATH. "application/www/pay/example/log.php";

//初始化日志
$logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
$payUrl = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

//①、获取用户openid
$tools = new JsApiPay();
// $openId = $tools->GetOpenid();
$openId = $_COOKIE["mb_web_traffic_openid"];

$orderId = trim($_GET["orderId"]);
$outTradeNo = rand(100000, 999999) . time() . rand(100000, 999999);

$totalFee = 0;
$mobile = "";
$scope = "";
$product = null;

$order = $db->getRow("select * from " . table("order") . " where id = '$orderId' and openid = '$openId'");

if (!$order) {
	errback("订单数据不存在");
}

$product = $db->getRow("select * from " . table("product") . " where id = '" . $order["product_id"] . "'");

$outTradeNo = $order["out_trade_no"];
$totalFee = $order["bonues_price"] * 100;
$mobile = $order["phone"];
$scope = $order["mobile_type"];

//②、统一下单
$jsApiParameters = "";
try {
	$input = new WxPayUnifiedOrder();
	$input->SetBody($product["name"]);
	$input->SetAttach($product["name"]);
	$input->SetOut_trade_no($outTradeNo);
	$input->SetTotal_fee($totalFee);
	//测试账号 支付金额为1分
 	if($openId == "oHbw8tyal64ZeOEXuQGxinCZbSs0") {
 	$input->SetTotal_fee(1);
 	}
	$input->SetTime_start(date("YmdHis"));
	$input->SetTime_expire(date("YmdHis", time() + 600));
	$input->SetNotify_url("http://www.chipshare.cn/ego/application/www/pay/payDetail_notify.php");
	$input->SetTrade_type("JSAPI");
	$input->SetOpenid($openId);
	$order = WxPayApi::unifiedOrder($input);
	$jsApiParameters = $tools->GetJsApiParameters($order);
} catch(Exception $e) {
	header("location: $payUrl");
	exit();
}
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title><?php echo $product["name"]; ?></title>
    <link rel="stylesheet" href="http://www.chipshare.cn/ego/application/www/css/wap/e_alipay.css?t=2" type="text/css">
    <link type="text/css" rel="stylesheet" href="http://www.chipshare.cn/ego/application/www/css/zepto.alert.css" />
	<script type="text/javascript" src="http://www.chipshare.cn/ego/application/www/js/jquery.js"></script>
	<script type="text/javascript" src="http://www.chipshare.cn/ego/application/www/js/zepto.alert.js"></script>
	<script type="text/javascript" src="http://www.chipshare.cn/ego/application/www/js/common_fun.js"></script>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				switch(res.err_msg) {
		            case 'get_brand_wcpay_request:cancel':
				       break;
		            case 'get_brand_wcpay_request:fail':
		            	alertWithTime("支付失败, 请长按二维码支付", 1500);
			            $("#qr_area").show();
				       break;
		            case 'get_brand_wcpay_request:ok':
			            alertWithTime("支付成功",2000);
			            setTimeout(function() {
								location.href='http://www.chipshare.cn/ego/application/www/wap.php?m=order';
				            }, 2000);
				       break;
		            default:
		            	break;
				}
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>
</head>

<div class="pageHead">
    <img width="100%" src="http://www.chipshare.cn//ego/application/www/images/banner.jpg">
</div>
<div class="mask">
    <div class="tabContent">
        <div class="sureRecharge tabBody ">
            <div class="tabItem">
                <div class="tabName inline">充值号码：</div>
                <div class="tabContentValue inline mobile"><?php echo $mobile; ?></div>
            </div>
            <div class="tabItem">
                <div class="tabName inline">号码归属：</div>
                <div class="tabContentValue inline belong"><?php echo $scope; ?></div>
            </div>
            <div class="tabItem">
                <div class="tabName inline">充值流量：</div>
                <div class="tabContentValue inline rechargeFlowNum"><?php echo $product["mb_value"]; ?>M</div>
            </div>
            <div class="tabItem">
                <div class="tabName inline">有效时间：</div>
                <div class="tabContentValue inline time">生效日起当月</div>
            </div>
            <div class="tabItem">
                <div class="tabName inline">支付金额：</div>
                <div class="tabContentValue inline money"><?php echo $product["bonues_price"]; ?>元</div>
            </div>
            <div class="buttonGroup">
                <div class="sure prevButton" onClick="history.go(-1)">上一步</div>
                <div class="sure sureButton" onclick="callpay();">确&nbsp;&nbsp;定</div>
            </div>
        </div>

        <div class="exchange tabBody negtive">
            <img src="./充值_files/buildExchange.png">
            <span>正在建设中</span>
        </div>

    </div>

</div>

   <div class="ewm" id="qr_area" style="display:none">
        <div class="ewm_img">
        	<div class="close"><span>X</span></div>
        	<img src="/qrcode.php?data=<?php echo urlencode($payUrl);?>">
            <div class="ewm_txt">
            	<span>长按二维码,立即支付。</span>
            </div>
        </div>
        
   </div>
<script type="application/javascript" >
$(".close").on("click",function(){
	$(this).parents(".ewm").hide();
});
</script>
</body>
</html>